package com.efivestar.idm.api.service.lock.protocol.handler;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.efivestar.idm.api.common.Cons;
import com.efivestar.idm.api.domain.EventDomain;
import com.efivestar.idm.api.exception.ErrorParamException;
import com.efivestar.idm.api.repository.EventMapper;
import com.efivestar.idm.api.service.DeviceService;
import com.efivestar.idm.api.service.dto.PowerDto;
import com.efivestar.idm.api.util.ByteUtils;

import io.netty.buffer.ByteBuf;

@Service
public class DefenseLockProtocolHandler extends AbstractLockProtocolHandler{

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private EventMapper mapper;

    /**
     * @param buf
     * @param lockId
     * @return
     */
    @Override
    public byte[] handleData(ByteBuf buf, String lockId) {
        int length = buf.readableBytes();
        //跳过指令码，不读取
        buf.skipBytes(1);
//        读取电量字节
        byte powerBt = buf.readByte();
        PowerDto power = ByteUtils.getPower(powerBt);
//        读取状态
        byte status = buf.readByte();

        int subEventType = getEventType(status);
        int defenseStatus = 0;
        if (subEventType == Cons.DEFENCE_OFF_EVENT) {
            defenseStatus = Cons.DEFENSE_OFF_STATUS;
        } else if (subEventType == Cons.DEFENCE_ON_EVENT) {
            defenseStatus = Cons.DEFENSE_ON_STATUS;
        }
        //读取imei(设备编号)
        // String lockId = String.valueOf(buf.readCharSequence(length - getDataLenthWithoutDeviceId(), Charset.forName("utf-8")));
        //设置设备的电量和更新时间
        deviceService.updatePowerAndDefenseStatus(lockId, power.getPowerPercent(), defenseStatus);

        EventDomain event = EventDomain.builder().deviceId(lockId).eventType(Cons.DEFENCE_EVENT_TPE).subEventType(subEventType).createTime(new Date()).build();
        mapper.insert(event);

        return ByteUtils.hexToBytes("00");

    }

    @Override
    protected int getDataLenthWithoutDeviceId() {
        return 3;
    }


    /**
     * 获取开门的子事件类型.
     * @param eventTypeBt
     * @return
     */
    private int getEventType(byte eventTypeBt) {
        String eventType = ByteUtils.bytes2hex(eventTypeBt);
        switch (eventType) {
            case "00":
                return Cons.DEFENCE_OFF_EVENT;
            case "01":
                return Cons.DEFENCE_ON_EVENT;
        }
        throw new ErrorParamException();
    }

    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        System.arraycopy(src, begin, bs, 0, count);
        return bs;
    }

    @Override
    public String udpHead(){
        return Cons.UDP_HEAD_EF01;
    }

    @Override
    public String udpCommand(){
        return Cons.UDP_COMMAND_DEFENSE;
    }





}






